import { Cascader, Col, DatePicker, Form, Input, Row, Select } from "antd";
import React, { forwardRef, useImperativeHandle } from "react";
import city from "@/enums/city";
const { RangePicker } = DatePicker;

type ArrItems = {
	name: string;
	label: string;
	placeholder?: string;
	rules?: any[];
	options?: any[] | any;
	type: string;
};

interface FormItemsProps {
	itemProps: ArrItems[];
	callback: (val: any) => void;
}

// 根据类型渲染不同 搜索类型
const TypeItem = (item: ArrItems) => {
	switch (item.type) {
		case "1": {
			return (
				<Form.Item style={{ marginRight: "5px" }} label={item.label} name={item.name} rules={item.rules || [{ required: false }]}>
					<Input placeholder={item?.placeholder || `请输入${item.label}`} allowClear />
				</Form.Item>
			);
		}
		case "2": {
			return (
				<Form.Item style={{ marginRight: "5px" }} label={item.label} name={item.name} rules={item.rules || [{ required: false }]}>
					<Select placeholder={item?.placeholder || `请输入${item.label}`} options={item.options || []} allowClear></Select>
				</Form.Item>
			);
		}
		case "3": {
			return (
				<Form.Item style={{ marginRight: "5px" }} label={item.label} name={item.name} rules={item.rules || [{ required: false }]}>
					<DatePicker placeholder={item?.placeholder || `请输入${item.label}`} allowClear format="YYYY-MM-DD" />
				</Form.Item>
			);
		}
		case "4": {
			return (
				<Form.Item style={{ marginRight: "5px" }} label={item.label} name={item.name} rules={item.rules || [{ required: false }]}>
					<RangePicker allowClear format="YYYY-MM-DD" />
				</Form.Item>
			);
		}
		case "5": {
			return (
				<Form.Item style={{ marginRight: "5px" }} label={item.label} name={item.name} rules={item.rules || [{ required: false }]}>
					<RangePicker showTime={{ format: "HH:mm:ss" }} format="YYYY-MM-DD HH:mm:ss" />
				</Form.Item>
			);
		}
		case "6": {
			return (
				<Form.Item style={{ marginRight: "5px" }} label={item.label} name={item.name} rules={item.rules || [{ required: false }]}>
					<Cascader options={city} placeholder="请选择省市区" />
				</Form.Item>
			);
		}
	}
};

// eslint-disable-next-line react/display-name
const FormItems = forwardRef(({ itemProps, callback }: FormItemsProps, ref: any) => {
	const [form] = Form.useForm();

	useImperativeHandle(ref, () => ({
		reset: () => {
			form.resetFields();
		}
	}));

	const rows = [];
	for (let i = 0; i < itemProps.length; i += 4) {
		const currentItems = itemProps.slice(i, i + 4);
		const cols = currentItems.map((item, index) => (
			<Col span={6} key={i + index}>
				{TypeItem(item)}
			</Col>
		));
		rows.push(<Row key={i}>{cols}</Row>);
	}

	return (
		<div>
			<Form
				form={form}
				style={{ paddingTop: "10px" }}
				// layout="vertical"
				// layout="horizontal"
				onChange={() => {
					callback(form.getFieldsValue());
				}}
				onValuesChange={() => {
					callback(form.getFieldsValue());
				}}
			>
				{rows}
			</Form>
		</div>
	);
});

export default FormItems;
